package main

import (
	"github.com/bitly/go-simplejson"
	"sync"
	"time"
)

func init() {
	LoadConfigInit(configPath, configName)
	go cameraLastBeatUpdate()
	go cameraStatusMonitor()
	go deviceHeartbeatFunc()
	logger.Info("相机在线状态监测及设备在线状态上报(心跳机制)携程任务启动成功")
}

var heartbeatChan = make(chan *simplejson.Json, 1024)
var cameraMapLock sync.RWMutex

func deviceHeartbeatFunc() {
	ticker := time.NewTicker(deviceHeartbeatInterval)
	defer ticker.Stop()
	for range ticker.C {
		mqttAccessServer("heartbeat")
	}
}

func cameraLastBeatUpdate() {
	for payloadJson := range heartbeatChan {
		// 带错误处理的设备ID解析
		cameraId, err := payloadJson.Get("devId").String()
		if err != nil {
			logger.Errorf("Invalid device ID: %v", err)
			continue
		}
		camerasTimerMap[cameraId] = time.Now()
	}
}

func cameraStatusMonitor() {
	ticker := time.NewTicker(30 * time.Second)
	defer ticker.Stop()
	for range ticker.C {
		checkDeviceStatus()
	}
}

// 核心状态检查逻辑
func checkDeviceStatus() {
	// 获取基准时间（减少系统调用）
	now := time.Now()
	for cameraId, lastTime := range camerasTimerMap {
		// 计算当前时间与最后心跳时间的差值
		duration := now.Sub(lastTime)
		cameraInfoStruct := camerasInfoMap[cameraId]
		wasOnline := cameraInfoStruct.GetOnline()
		isOnline := duration <= cameraHeartbeatInterval
		if !isOnline {
			cameraMapLock.Lock()
			cameraInfoStruct.SetOnline(false)
			camerasInfoMap[cameraId] = cameraInfoStruct
			cameraMapLock.Unlock()
			logger.Errorf("相机离线,cameraId:%v", cameraId)
			handleCameraErrorShows(cameraInfoStruct.GetLedChannel(), cameraInfoStruct.GetLedAddress())
		} else {
			if wasOnline != isOnline {
				cameraInfoStruct.SetOnline(isOnline)
				camerasInfoMap[cameraId] = cameraInfoStruct
				logger.Infof("相机恢复在线状态,cameraId:%v", cameraId)
			}
		}
	}
}
